package backtrack;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

public class Solution47 {

    LinkedList<Integer> track = new LinkedList<>();
    List<List<Integer>> result = new LinkedList<>();
    public boolean[] visited;

    public List<List<Integer>> permuteUnique(int[] nums) {
        visited = new boolean[nums.length];
        Arrays.sort(nums);
        backTrack(nums);
        return result;
    }

    public void backTrack(int[] nums){
        if (track.size()== nums.length){
            result.add(new ArrayList<>(track));
        }

        for (int i = 0; i < nums.length; i++) {
            //做出选择
            if (visited[i]){
                continue;
            }
            if (i>0 && nums[i-1]==nums[i] && !visited[i-1]){
                continue;
            }
            visited[i]=true;
            track.add(nums[i]);

            backTrack(nums);

            visited[i]=false;
            track.removeLast();
        }
    }
}
